<?php
/**
 * Created by PhpStorm.
 * User: Keter
 * Date: 2016/7/28
 * Time: 20:25
 */

class GetPaiJuList extends ApiRedisBase
{
    public function logic()
    {
        $this->checkUser();

        $list = $nicknames = $sort = array();
        $paiZuID = $this->params['paiZuID'];

        if (empty($paiZuID)) {
            $this->returnError('no_paizu_id');
        }

        $redis = $this->redis('paiju_log');
        $paizuKeys = $redis->keys('PJL:' . $paiZuID . '*'); //获取牌局日志KEY
        $fields = array('seq', 'time', 'uids', 'detail');
        $i = 0;

        foreach ($paizuKeys as $key) {
            $row = $redis->hMget($key, $fields); //获取牌局日志信息
            if ($row) {
                $row['uids'] = json_decode($row['uids'], true);
                $row['detail'] = json_decode($row['detail'], true);
                if ($i == 0) {
                    $nicknames = $this->getNickname($row);
                }
                $row['users'] = $this->getScore($row);
                unset($row['uids'], $row['detail']);
                $list[] = $row;
                $sort[] = $row['seq'];
            }
            $i ++;
        }

        if ($list) {
            asort($sort, SORT_NUMERIC);
            array_multisort($list, SORT_ASC, $sort);
        }

        $list = $this->formatNumber($list);

        $data = ['nicknames' => $nicknames, 'list' => $list];
        $this->returnData('suc_action', $data);
    }

    /**
     * 获取用户昵称
     * @param $uids
     * @return array
     */
    public function getNickname($row)
    {
        $result = array();
        $redis = $this->redis('user_info');

        foreach ($row['uids'] as $key => $uid) {
            $userInfo = $redis->hMget('U:' . $uid, array('nickname'));
            if ($userInfo) {
                $result[$key] = $userInfo['nickname'];
            } else {
                $result[$key] = '';
            }
        }

        return $result;
    }

    public function getScore($data)
    {
        $score = $data['detail']['score'];
        $result = [];

        foreach ($data['uids'] as $key => $row) {
            $result[$key] = $score[$key][0];
        }

        return $result;
    }
}